package org.jash.sportnews2109.ui

import android.view.KeyEvent
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.tabs.TabLayoutMediator
import org.jash.common.mvvm.BaseFragment
import org.jash.sportnews2109.adapter.CategoryAdapter
import org.jash.sportnews2109.databinding.FragmentHomeBinding
import org.jash.sportnews2109.entity.Category
import org.jash.sportnews2109.vm.HomeViewModel

@Route(path = "/news/home")
class HomeFragment : BaseFragment<FragmentHomeBinding, HomeViewModel>() {
    val adapter by lazy { CategoryAdapter(this) }
    override fun initView() {
        binding.pager.adapter = adapter
        TabLayoutMediator(binding.tab, binding.pager) { t, p ->
            t.text = adapter.getTitle(p)
        }.attach()
        binding.search.editText.setOnEditorActionListener { v, _, event ->
            when(event.action) {
                KeyEvent.ACTION_DOWN -> {
                    ARouter.getInstance()
                        .build("/news/search")
                        .withString("key", v.text.toString())
                        .navigation()
                    binding.search.hide()
                }
            }
            true
        }
    }

    override fun initData() {
        viewModel.categoriesLiveData.observe(this, adapter::plusAssign)
        viewModel.loadCategories()
    }
}